<template>
  <a-popover
    :placement="placement"
    :trigger="trigger"
    arrow-point-at-center
    overlay-class-name="table-column-setting-popover"
    :auto-adjust-overflow="true"
  >
    <template slot="title">
      <div class="table-column-setting-title">
        <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="allColumnChange">
          {{$t('m.components.label.columnShow')}}
        </a-checkbox>
        <a href="#" @click="resetColumn" class="table-column-setting-reset">{{$t('m.common.button.reset')}}</a>
      </div>
    </template>
    <template slot="content">
      <div class="table-column-setting-list">
        <!-- 固定左侧的列 -->
        <ul class="table-column-setting-list-item">
          <li
            class="table-column-setting-list-item-li"
            v-for="(item, index) in fixedLeftColumns"
            :key="index"
            :title="item.title"
          >
            <a-checkbox
              :value="item.dataIndex"
              :checked="item.visible"
              @change="columnChange(item)"
            >
              {{ item.title }}
            </a-checkbox>
          </li>
        </ul>
        <ul class="table-column-setting-list-item">
          <draggable
            v-model="settingColumns"
            v-bind="dragOptions"
            handle=".li-drag"
            @start="drag = true"
            @end="dragEnd"
          >
            <transition-group type="transition" :name="!drag ? 'table-column-setting-flip-list' : null">
              <template v-for="(item, index) in settingColumns">
                <li
                  v-if="!item.fixed"
                  :key="index"
                  :title="item.title"
                  class="table-column-setting-list-item-li"
                >
                  <a-checkbox
                    :value="item.dataIndex"
                    :checked="item.visible"
                    @change="columnChange(item)"
                  >
                    {{ item.title }}
                  </a-checkbox>
                  <ych-icon type="drag"
                            class="li-drag"
                            style="
                        position: absolute;
                        right: 5px;
                        font-size: 1rem;
                        color: #888;
                        line-height: 26px;
                        cursor: move;"
                  ></ych-icon>
                </li>
              </template>
            </transition-group>
          </draggable>
        </ul>
        <!-- 固定右侧的列 -->
        <ul class="table-column-setting-list-item">
          <li
            class="table-column-setting-list-item-li"
            v-for="(item, index) in fixedRightColumns"
            :key="index"
            :title="item.title"
          >
            <a-checkbox
              :value="item.dataIndex"
              :checked="item.visible"
              @change="columnChange(item)"
            >
              {{ item.title }}
            </a-checkbox>
          </li>
        </ul>
      </div>
    </template>
    <a-icon type="setting" :style="{fontSize: '16px'}" :title="$t('m.components.title.columnSet')"/>
  </a-popover>
</template>

<script>
  import draggable from 'vuedraggable';
  import { mapGetters, mapActions } from 'vuex';
  export default {
    name: 'YchTableColSettings',
    components: {
      draggable,
    },
    props: {
      tableKey:{
        type: String
      },
      // 弹出框位置
      placement: {
        type: String,
        default: 'bottomRight'
      },
      // 触发方式
      trigger: {
        type: String,
        default: 'click'
      },
      // 记录的初始列设置columns
      initSettingColumns: {
        type: Array,
        default: () => []
      },
    },
    data() {
      return {
        settingColumns: [], // 内部的列设置columns
        indeterminate: false, // 列显隐全选按钮的半选状态的样式控制
        checkAll: true, // 列显隐全选按钮的全选与全不选标志
        dragOptions: {
          // 列表拖拽配置参数
          animation: 300,
          group: 'columnsSettingDragGroup',
          disabled: false,
          ghostClass: 'table-column-setting-ghost',
          forceFallback: true,
          fallbackClass: 'table-column-setting-drag-fallback'
        },
        drag: false // 列表拖拽状态
      }
    },
    computed: {
      /**
       * 引入个性化设置vuex的getter
       */
      ...mapGetters(['customTableColumns']),
      // 可响应个性化配置数据变化的模块列配置
      customCols(){
        return this.customTableColumns(this.tableKey)
      },
      fixedLeftColumns() {
        let leftCols = [];
        this.settingColumns.map(item => {
          if (item.fixed === 'left') {
            let fixLeftCol = Object.assign({}, item);
            leftCols.push(fixLeftCol);
          }
        });
        return leftCols;
      },
      fixedRightColumns() {
        let rightCols = [];
        this.settingColumns.map(item => {
          if (item.fixed === 'right') {
            let fixRightCol = Object.assign({}, item);
            rightCols.push(fixRightCol);
          }
        });
        return rightCols;
      }
    },
    methods: {
      ...mapActions(['loadCustomTableColumns']),
      /**
       * 改变所有字段的显隐
       */
      allColumnChange(e) {
        let columns = [...this.settingColumns];
        if (e.target.checked) {
          // 全选
          columns.map(item => {
            item.visible = true;
          });
          this.indeterminate = false;
          this.checkAll = true;
        } else {
          // 全不选
          columns.map(item => {
            item.visible = false;
          });
          this.indeterminate = false;
          this.checkAll = false;
        }
        this.settingColumns = columns;
        this.$nextTick(() => {
          this.columnShowChange();
        });
      },
      /**
       * 重置
       */
      resetColumn() {
        // 深拷贝，以免改变原数组
        let dealColumns = [];
        this.initSettingColumns.map(item => {
          let newObj = Object.assign({}, item);
          dealColumns.push(newObj);
        });
        this.settingColumns = dealColumns;
        this.$nextTick(() => {
          this.columnShowChange(true);
        });
      },
      /**
       * 改变单个字段的显隐
       */
      columnChange(column) {
        let columns = [...this.settingColumns];
        columns.map(item => {
          if (item.dataIndex == column.dataIndex) {
            item.visible = !item.visible;
          }
        });
        this.settingColumns = columns;
        this.$nextTick(() => {
          this.columnShowChange();
        });
      },
      allCheckStyle(fullColumn){
        let showNum = 0;
        fullColumn.map(item => {
          if (item.visible) {
            showNum++;
          }
        });
        this.checkAll = showNum > 0 && showNum == fullColumn.length;
        this.indeterminate = showNum > 0 && showNum < fullColumn.length;
      },
      /**
       * 列表拖拽end事件
       */
      dragEnd() {
        this.drag = false;
        this.$nextTick(() => {
          this.columnShowChange();
        });
      },
      /**
       * 列显隐变化传回父组件事件
       */
      columnShowChange(isReset) {
        this.allCheckStyle(this.settingColumns);
        this.$emit('customColumnChange', this.settingColumns);
        let storeCustomColumns = []
        //不是重置保存个性化配置，重置传空
        if(!isReset){
          storeCustomColumns = this.settingColumns.map(item=>{
            let newItem = {
              dataIndex:item.dataIndex,
              visible:item.visible
            }
            return newItem
          })

        }
        //保存个性化列设置
        this.$store.commit('SAVE_CUSTOM_TABLE_COLUMNS', {
          key:this.tableKey,
          val: storeCustomColumns
        });
      },
      dealCustomColumns(){
        let customColumns = this.customCols
        if(customColumns){
          if(customColumns.length<1){
            //深拷贝
            let newInitSettingColumns = []
            for(let i=0;i<this.initSettingColumns.length>0;i++){
              let newObj = Object.assign({}, this.initSettingColumns[i]);
              newInitSettingColumns.push(newObj)
            }
            this.settingColumns = newInitSettingColumns
            return
          }
          const columns = [...this.initSettingColumns]; // 表格所有字段
          let realColumns = []; // 排序后的真实columns
          for (let i = 0; i < customColumns.length; i++) {
            for (let j = 0; j < columns.length; j++) {
              // 个性化表格设置不为空,则获取个性化表格设置与表格所有字段的公共部分
              if (columns[j].dataIndex === customColumns[i].dataIndex) {
                let newObj = Object.assign({}, columns[j]);
                newObj.visible = customColumns[i].visible;
                realColumns.push(newObj);
              }
            }
          }
          // 追加授权变化等新增的列
          for (let i = 0; i < columns.length; i++) {
            let isSet = false;
            realColumns.map(item => {
              if (item.dataIndex === columns[i].dataIndex) {
                isSet = true;
              }
            });
            if (!isSet) {
              columns[i].visible = true;
              realColumns.push(columns[i]);
            }
          }
          // 按固定列左右排列
          let sortedColumns = [];
          realColumns.map(item => {
            if (item.fixed === 'left') {
              sortedColumns.push(item);
            }
          });
          realColumns.map(item => {
            if (!item.fixed) {
              sortedColumns.push(item);
            }
          });
          realColumns.map(item => {
            if (item.fixed === 'right') {
              sortedColumns.push(item);
            }
          });
          this.settingColumns =  sortedColumns
          this.allCheckStyle(this.settingColumns);
          this.$emit('customColumnChange', this.settingColumns);
        }else{
          this.loadCustomTableColumns(this.tableKey)
        }
      },
    },
    watch: {
      initSettingColumns:{
        immediate: true,
        handler(val) {
          if(val){
            this.dealCustomColumns()
          }

        }
      },
      customCols:{
        immediate: true,
        handler(val) {
          if(val){
            this.dealCustomColumns()
          }

        }
      }
    },
  }
</script>

<style lang="less">

  /* Start 列显隐样式 */
  .table-column-setting-popover .ant-popover-inner-content {
    max-height: 260px;
    overflow-y: auto;
  }
  /* 列显隐列表的滚动条样式 */
  .table-column-setting-popover .ant-popover-inner-content::-webkit-scrollbar-thumb {
    border-width: 0 0 0 9px;
  }
  .table-column-setting-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 32px;
    .ant-checkbox-wrapper{
      font-size: 12px;
    }
  }
  .table-column-setting-list {
    display: flex;
    flex-direction: column;
    width: 168px;
    .table-column-setting-list-item {
      display: block;
      width: 100%;
      list-style: none;
      .table-column-setting-list-item-li {
        position: relative;
        width: 100%;
        height: 30px;
        padding-right: 0.8rem;
        .ant-checkbox-wrapper {
          margin-bottom: 8px;
          margin-left: 0;
          width: 100%;
          font-size: 12px;
          height: 22px;
          line-height: 22px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space:nowrap;
        }
      }
    }
  }
  /* End 列显隐样式 */
  /* Start 拖拽相关 */

  .table-column-setting-ghost {
    opacity: 0.8;
  }

  .table-column-setting-drag-fallback {
    opacity: 0 !important;
  }

  /* End 拖拽相关 */

</style>
